<?php
namespace control;
/*
*培训计划类
*/

class trainingPlanClass extends adIndexClass
{
    private const page = 'trainingPlan';
    private const table = 'training_plan';
    private const tableMx = 'training_plan_detail';
    private const title = '培训计划';
    public array $stateOption = ['草稿', '审核中', '已通过'];

    /*列表-查询条件*/
    public function home()
    {
        //生成查询表单
        $html =
            text(array("name" => "orderNo", "title" => L('recruitment.table.orderNo'))) .
            text(array("name" => "name", "title" => L('trainingPlan.table.planName'))) .
            selectMultiple(array("name" => "stid", "title" => L('recruitment.table.prepared'), "table" => "staff", 'sqlField' => 'name', 'sqlId' => 'stid')) .
            text(array("name" => "createTime", 'class' => 'width200', 'laydate' => ['type' => 'date', 'range' => '~'], "title" => L('recruitment.table.createTime') . "-" . L('recruitment.table.createTime'))) .
            select(array("name" => "state", "title" => L('trainingPlan.table.state'), "option" => $this->stateOption));
        //返回
        return $this->homeFun($this->search($html));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),//单据编号
            "name" => $this->post('name'),//计划名称
        );
        //全等查询数组
        $equal = array(
            "state" => $this->post('state'),//状态
            "stid" => $this->post('stid'),//申请人
        );
        $and = $this->seeSelf(self::page, 'stid');
        if ($this->post('createTime')) {
            $timeArr = explode(' ~ ', $this->post('createTime'));
            $and .= " and date(time) >='{$timeArr[0]}' and  date(time) <='{$timeArr[1]}'";
        }
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => "time desc"));
        //获取表头
        $checkAll = $this->checkAll("listForm", "listId");
        $tr[] = array($checkAll, L('recruitment.table.orderNo'), L('trainingPlan.table.planName'), L('trainingPlan.table.planStartAndEnd'), L('recruitment.table.staffDept'), L('recruitment.table.prepared'), L('recruitment.table.createTime'), L('trainingPlan.table.state'));
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => L('trainingPlan.table.plan'), "click" => "newIframe('" . L('trainingPlan.table.plan') . "','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );

            $tr[] = array($this->dominate($dominate), $array['orderNo'], $array['name'], $array['startDate'] . ' ~ ' . $array['endDate'], $array['deptName'], self::findStaff($array['stid']), $array['time'], $array['state']);
        }
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . L('trainingPlan.table.plan') . "','" . $url . "&fun=edit')\" class='spanButton'>" . L('recruitment.table.add') . "</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">" . L('recruitment.table.del') . "</span>\n";
        }
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id') ?: suiji();
        $info = query(self::table, " id = '" . $id . "' ");
        //表单
        $data['html'] = $this->layerEdit([
            "table" => [
                [
                    must . L('trainingPlan.table.planName')."：" => text(array('name' => 'name', 'value' => $info['name'])),
                ],
                [
                    must . L('trainingPlan.table.planStartAndEnd')."：" => text(["name" => "chooseDate", 'class' => 'select', 'laydate' => ['range' => '~'], "value" => $info['id'] ? ($info['startDate'] . ' ~ ' . $info['endDate']) : '']),
                ],
                [
                    L('staffProfiles.table.text')."：" => textarea(["name" => "text", "value" => $info['text']])
                        . hidden(['name' => 'id', 'value' => $info['id'] ?: $id]),
                ],
            ],
            'button' => '<button class="button left-bottom" onclick="subForm(\'' . self::page . 'EditForm\',root+\'control/adIndex.html?cla=' . self::page . '&fun=editEdit\')">'.L('staffProfiles.table.save').'</button>',
        ]);


        //返回
        return $this->tab($data);
    }

    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $timeArr = $this->post('chooseDate') ? explode(' ~ ', $this->post('chooseDate')) : [];
        $field = [
            'name' => $this->post('name'),
            'startDate' => $timeArr[0],
            'endDate' => $timeArr[1],
            'text' => $this->post('text'),
            'updateTime' => $this->time
        ];
        $annotation = [
            'name' => L('trainingPlan.table.planName'),
            'startDate' => L('trainingPlan.table.planStartAndEnd'),
            'endDate' => L('trainingPlan.table.planStartAndEnd'),
        ];
        $rules = [
            'name' => 'required',
            'startDate' => 'required',
            'endDate' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('trainingPlan.table.edit_permission');
        } else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $department = query('department', " id = '{$this->controlJob['departmentId']}'");
                $userNo = codeTemplateClass::generateCode(self::page, [
                    'prefix' => 'PXJH' . date('Ymd'),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ], $field);
                $field = array_merge($field, [
                    'id' => $id,
                    'orderNo' => $userNo,
                    'deptName' => $department['name'],
                    'stid' => $this->control['stid'],
                    'state' => '草稿',
                    'time' => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $text = str_replace(['{{staffName}}','{{name}}','{{id}}'],[$this->control['name'],$field['name'],$id],L('trainingPlan.table.plan_edit_log'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /*数据导入分析*/
    public function import()
    {
        $id = $_SESSION[self::page]['id'];
        $info = query(self::table, " id = '$id'");
        if (!$this->power(self::page, 'import')) {
            $_SESSION['warn'] = L('staffProfiles.tip.permission_import_warn');
        } elseif (empty($info['id'])) {
            $_SESSION['warn'] = L('trainingPlan.table.no_plan');
        } else {
            $data = $this->importHead();
            $x = 0;
            $text = '';
            foreach ($data as $i => $row) {
                if ($i > 0) {
                    $cell = formSubArray($row);
                    $field = [
                        'id' => self::getId(),
                        'orderId' => $info['id'],
                        'time' => $this->time,
                        'type' => $cell[0],
                        'project' => $cell[1],
                        'trainingTime' => $cell[2],
                        'hour' => $cell[3],
                        'budget' => $cell[5],
                        'department' => $cell[4],
                        'trainingObject' => $cell[6],
                    ];
                    $annotation = [
                        'type' => L('trainingPlan.table.trainingType'),
                        'project' => L('trainingPlan.table.trainingProject'),
                        'trainingTime' => L('trainingPlan.table.trainingTime'),
                        'hour' => L('trainingPlan.table.hours'),
                    ];
                    $rules = [
                        'type' => 'required',
                        'project' => 'required',
                        'trainingTime' => 'required',
                        'hour' => 'required',
                    ];
                    // 校验是否符合规则
                    $vt = new \verify();
                    $line = str_replace(['{{i}}'], [$i], L('job.other.line'));
                    $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
                    if ($result === false) {
                        $text .= $line."：" . $vt->getErrs()[0] . "<br>";  // 多个规则提示最前面一条
                    } else {
                        $warn = insert(["table" => self::table, "field" => $field]);
                        if (in_array($warn, ["新增成功", "更新成功"])) {
                            $x++;
                            $text .= $line."：".L('job.other.import_success')."<br>";
                        } else {
                            $text .= $line."：".L('job.other.import_failed')."<br>";
                        }
                    }
                }
            }
            $text =str_replace(['{{staffName}}','{{fileName}}'],[$this->control['name'],$_FILES['file']['name']],L('job.other.import_log'))  .  '：' . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $warn = str_replace(['{{$x}}'],[$x],L('job.other.import_warn'));
            $_SESSION['warn'] = $warn;
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }


    /**
     * 导出
     */
    public function exportData()
    {
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] =  L('staffProfiles.tip.permission_export_warn');
        } else {
            $data = [];
            $id = $_SESSION[self::page]['id'];
            $info = query(self::table, " id = '$id'");
            $title = [L('trainingPlan.table.trainingType'), L('trainingPlan.table.trainingProject'), L('trainingPlan.table.trainingTime'),
                L('trainingPlan.table.hours').'(h)', L('trainingPlan.table.speakerDept'), L('trainingPlan.table.budget').'(' . static::$unit . ')', L('trainingPlan.table.trainMember')];
            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$id' order by time asc"));
            if (is_array($result['array'])) {
                foreach ($result['array'] as $array) {
                    $data[] = [$array['type'], $array['project'], $array['trainingTime'], $array['hour'], $array['department'], $array['budget'], $array['trainingObject']];
                }
            }
            $text = str_replace(['{{staffName}}','{{name}}'],[$this->control['name'],$info['name']],L('trainingPlan.table.export_text'));
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, str_replace(['{{name}}'],[$info['name']],L('trainingPlan.table.export_name')).".xlsx");
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }

    /**
     * 审核按钮
     * @param $info
     * @return array
     */
    public function auditButton($info): array
    {
        $button = [];
        if ($info['state'] == '草稿' || auditClass::auditFlag(self::table, $info['id'], 'selfChoose')) {
            $button[] = [
                "name" => L('recruitment.table.commitAudit'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                'style' => 'li-btn-blue-bg',
                "post" => ["act" => 'start', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'name' => '培训计划',
                    'table' => self::table,
                    'process' => [
                        // 预览函数
                        'detail' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'detail'
                        ],
                        // 保存函数
                        'save' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'editEdit'
                        ],
                        //执行发起时验证函数
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
            ];
        }
// 审批并判断是否有权限
        if ($info['state'] == '审核中' && auditClass::auditFlag(self::table, $info['id'])) {
            $button[] = [
                "name" => L('recruitment.table.audit'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                // 以下参数固定格式
                "post" => ["act" => 'approval', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿', '已通过'],
                    ],
                    // 审核时回调
                    'process' => [
                        //执行首次审核时验证
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //执行末次审核后处理
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
                'style' => 'li-btn-blue-bg',
            ];
            $button[] = [
                "name" => L('recruitment.table.addAudit'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'addApprover', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];
            $button[] = [
                "name" => L('recruitment.table.transmit'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'transfer', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];

        }

        // 撤销审批
        if (auditClass::auditFlag(self::table, $info['id'], 'cancel') && $info['state'] != '草稿') {
            $button[] = [
                "name" => L('recruitment.table.cancel'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'cancel', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿'],
                    ],
                    'process' => [
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
            ];
        }
        return $button;
    }

    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = L('trainingPlan.table.no_plan');
        } else {
            $audit = query('audit', " targetId = '$info[id]'");
            //菜单
            $data = array(
                "id" => $info['id'],
            );
            $mxButton = '';//招聘目标按钮
            $button = [];
            if ($this->power(self::page, "edit") && $info['state'] == '草稿') {
                //按钮
                $button[] = [
                    "name" => L('recruitment.table.del'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
                //按钮
                $button[] = [
                    "name" => L('recruitment.table.edit'),
                    "type" => "顶部页卡",
                    "title" => L('recruitment.table.edit'),
                    "url" => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=edit&id=' . $info['id'],

                ];
                $mxButton = "<span class='spanButton' style='margin-left:0' onclick=\"layer('" . self::page . "','addMx',{id:'" . self::getId() . "',mainId:'" . $info['id'] . "'})\">".L('job.model.edit')."</span>
<span class='spanButton' onclick=\"layer('" . self::page . "','operate',{id:'" . $info['id'] . "',act:'delMx'})\">".L('staffProfiles.button.del')."</span>
" . $this->upButton(array("title" =>L('staffProfiles.button.import'), "fun" => "import")) . "
<a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportData'><span class='spanButton'>".L('staffProfiles.button.export')."</span></a>";
            }
            //审核按钮
            $button = array_merge($button, $this->auditButton($info));

            $_SESSION[self::page]['id'] = $info['id'];
            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by time asc"));
            $checkAll = $this->checkAll("detailForm", "mxId");
            $tr[] = [$checkAll, L('trainingPlan.table.trainingType'), L('trainingPlan.table.trainingProject'), L('trainingPlan.table.trainingTime'), L('trainingPlan.table.hours').'(h)', L('trainingPlan.table.speakerDept'), L('trainingPlan.table.budget').'(' . static::$unit . ')', L('trainingPlan.table.trainMember')];
            foreach ($result['array'] as $array) {
                //列表控件
                $dominate = array(
                    "box" => array("name" => "mxId", "value" => $array['id']),
                    'edit' => array('title' => L('recruitment.table.edit'), 'click' => "layer('" . self::page . "','addMx',{id:'" . $array['id'] . "',mainId:'" . $info['id'] . "'})")
                );
                $tr[] = [$this->dominate($dominate), $array['type'], $array['project'], $array['trainingTime'], $array['hour'], $array['department'], $array['budget'], $array['trainingObject']];
            }

            //生成表单
            $data['html'] = $this->tableShow(array(
                "button" => $button,
                array(
                    array(
                        L('recruitment.table.orderNo') => $info['orderNo'],
                        L('trainingPlan.table.planName') => $info['name'],
                        L('trainingPlan.table.planStartAndEnd') => $info['startDate'] . ' ~ ' . $info['endDate'],
                    ),
                    array(
                        L('recruitment.table.staffDept') => $info['deptName'],
                        L('recruitment.table.prepared') => self::findStaff($info['stid']),
                        L('department.table.creatTime') => $info['time'],
                    ),
                    array(
                        L('recruitment.table.commitTime') => self::null($audit['commitTime']),
                        L('trainingPlan.table.state') => $info['state'],
                    ),
                    array(
                        L('trainingPlan.table.text') => $info['text'],
                    ),
                ),
                L('trainingPlan.table.planMx') => array(
                    array(
                        "<div>{$mxButton}</div>
                        <div class='purchaseMx' style='margin-top: 5px'><form name='detailForm'>" . hidden(array('name' => 'id', 'value' => $info['id'])) . $this->tableMany(array('tr' => $tr)) . "</form></div>"
                    ),
                ),
                L('recruitment.table.flow') => array(
                    array(
                        auditClass::auditRecord(self::table, $info['id'])
                    )
                ),
            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }


    /**
     * 新增培训计划明细
     * @return bool|string
     */
    public function addMx()
    {
        $mx = query(self::tableMx, " id = '{$this->post('id')}'");
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                must . L('trainingPlan.table.trainingType')."：" => select(array('name' => 'type', 'class' => 'select', 'value' => $mx['type'], 'option' => explode('，', para('trainingType')))),
            ),
            array(
                must . L('trainingPlan.table.trainingProject')."：" => text(array('name' => 'project', 'class' => 'text', 'value' => $mx['project']))
            ),
            array(
                must . L('trainingPlan.table.trainingTime')."：" => text(array('name' => 'trainingTime', 'class' => 'text', 'value' => $mx['trainingTime']))
            ),
            array(
                must . L('trainingPlan.table.hours')."：" => text(array('name' => 'hour', 'class' => 'text', 'unit' => 'h', 'value' => $mx['hour']))
            ),
            array(
                L('trainingPlan.table.speakerDept')."：" => text(array('name' => 'department', 'class' => 'text', 'value' => $mx['department']))
            ),
            array(
                L('trainingPlan.table.budget')."：" => text(array('name' => 'budget', 'class' => 'text', 'unit' =>  static::$unit , 'value' => $mx['budget']))
            ),
            array(
                L('trainingPlan.table.trainMember')."：" => text(array('name' => 'trainingObject', 'class' => 'text', 'value' => $mx['trainingObject']))
            )
        ),
            'hidden' => hidden(array('name' => 'mainId', 'value' => $this->post('mainId')))
        ));
        //返回
        return $this->layer(array("title" => L('trainingPlan.table.recordMx'), "height" => 400, "width" => 700, "html" => $html));
    }

    /**
     * 培训计划明细编辑
     * @return bool|string
     */
    public function addMxEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $field = [
            'type' => $this->post('type'),
            'project' => $this->post('project'),
            'trainingTime' => $this->post('trainingTime'),
            'hour' => $this->post('hour'),
            'budget' => $this->post('budget'),
            'department' => $this->post('department'),
            'trainingObject' => $this->post('trainingObject'),
        ];
        $annotation = [
            'type' => L('trainingPlan.table.trainingType'),
            'project' => L('trainingPlan.table.trainingProject'),
            'trainingTime' => L('trainingPlan.table.trainingTime'),
            'hour' => L('trainingPlan.table.hours'),
        ];
        $rules = [
            'type' => 'required',
            'project' => 'required',
            'trainingTime' => 'required',
            'hour' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        $info = query(self::table, " id = '" . $this->post('mainId') . "' ");
        $infoMx = query(self::tableMx, " id = '" . $id . "' ");
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('trainingPlan.table.edit_permission');
        } elseif (empty($info['id'])) {
            $json['warn'] = L('trainingPlan.table.no_plan');
        } elseif ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
        } else {
            if (empty($infoMx['id'])) {
                $field = array_merge(
                    $field,
                    [
                        'id' => $id,
                        'orderId' => $info['id'],
                        'time' => $this->time,
                    ]
                );
                $json['warn'] = static::insert(array(
                    "table" => self::tableMx,
                    "field" => $field,
                ));
            } else {
                //更新员工档案
                $json['warn'] = update(array(
                    "table" => self::tableMx,
                    "field" => $field,
                    "where" => "id = '$infoMx[id]'",
                ));
            }

            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $text = str_replace(['{{staffName}}','{{name}}','{{id}}'],[$this->control['name'],$field['project'],$id],L('trainingPlan.table.planMx_edit_log'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        //返回
        return json_encode($json, 320);
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            case 'delMx':
                $act = 'del';
                $msg = L('trainingPlan.table.delMx');
                $title = self::page . 'DeleteMx';
                $function = 'deleteMx';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                break;
            default:
                $act = 'del';
                $msg = L('trainingPlan.table.delPlan');
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('recruitment.table.msg'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('recruitment.table.del_per');
        } elseif (empty($array)) {
            $json['warn'] = L('recruitment.table.no_data');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] != '草稿') {
                    $warn = L('recruitment.table.draft');
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                    //删除audit表记录
                    delete(array('table' => 'audit', 'where' => "targetId = '$id'"));
                    //删除待办事项
                    delete(array("table" => "backlog", "where" => " typeId = '$id' "));
                    //删除审批记录
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //删除消息提醒
                    delete(array("table" => "message", "where" => " typeId = '$id' "));
                    //返回
                    $warn = L('recruitment.table.del_suc');
                    $x++;
                }
                $text .= str_replace(['{{name}}', '{{orderNo}}', '{{id}}'], [$info['name'], $info['orderNo'], $info['id']], L('trainingPlan.table.plan_del_text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('trainingPlan.table.plan_del_log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('trainingPlan.table.plan_del_warn'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 删除培训明细
     * @return bool|string
     */
    public function deleteMx()
    {
        $array = $this->post('mxId');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('recruitment.table.del_per');
        } elseif (empty($array)) {
            $json['warn'] = L('recruitment.table.no_data');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $mx = query(self::tableMx, " id = '$id' ");
                $info = query(self::table, " orderId = '$id' ");
                if ($info['state'] != '草稿') {
                    $warn = L('recruitment.table.draft');
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                    //返回
                    $warn = L('recruitment.table.del_suc');
                    $x++;
                }
                $text .= str_replace(['{{type}}', '{{project}}', '{{id}}'], [$mx['type'], $mx['project'], $mx['id']], L('trainingPlan.table.planMx_del_text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('trainingPlan.table.planMx_del_log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('trainingPlan.table.planMx_del_warn'));
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }
}

